<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!taskDefKey && !isConsultation">
    <!-- 用车申请详情 -->
    <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
                  :rules="editModel != 0 ? rules : {}">
      <a-spin :spinning="loading[0] || loading[1]">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name :title="taskDefKey ? '用车申请信息' : '基本信息'"></title-name>
          <custom-form :formList="formList" :form="form" :editModel="editModel == 0 ? 'V' : ''">
            <!-- 人员 -->
            <template #usePersonId>
              <a-tag class="mb12" v-for="person in form.usePersonId" :key="person.userId"
                     :closable="editModel != 0"
                     @close="form.usePersonId = form.usePersonId.filter((item) => person.userId !== item.userId)"
                     color="#108ee9">
                {{ person.name }}
              </a-tag>
              <a-button v-if="editModel != 0" @click="visible = true"
                        :class="{ ml12: form.usePersonId && form.usePersonId.length > 0 }">
                添加人员
              </a-button>
              <span
                    v-if="editModel == 0 && (!form.usePersonId || form.usePersonId.length === 0)">无</span>
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top" v-if="!taskDefKey">
        <a-button :loading="loading[0]" :disabled="loading[1]"
                  v-if="(editModel == 1 && (statusCode == '0' || statusCode == '3')) || editModel == 2"
                  type="primary" class="button_right" @click="handleSubmit(0)">
          {{ statusCode == '2' || statusCode == '3' ? '保存' : '保存草稿' }}
        </a-button>
        <a-button :loading="loading[1]" :disabled="loading[0]" v-if="
            (editModel == 1 && (statusCode == '0' || statusCode == '3')) ||
            editModel == 2 ||
            (editModel != 0 && statusCode == '2')
          " type="primary" class="button_right" @click="handleSubmit(1)">
          提交
        </a-button>
        <a-button v-if="checkVisibleInDetail && !isConsultation" type="primary"
                  @click="handleActiveClose">
关闭
</a-button>
      </div>
    </a-form-model>
    <!-- 人员选择 -->
    <SelectPersonModal :personsList="form.usePersonId" :visible.sync="visible"
                       :form="{ rootOrgId: form.unitId }" :needTree="false" isMutilple isConfirm @confirmSelects="confirmSelects" />
    <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { carApplication } from '@/api/office/vehicle/config' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import { createValidator, isPhone } from '@/utils/regExpression' // 正则校验
import SelectPersonModal from '@/components/SelectPersonModal' // 人员

export default {
  extends: new BaseEditPage(),
  components: {
    SelectPersonModal
  },
  data() {
    const timeValidator = (rule, value, callback) => {
      if (!value || value.length === 0) {
        callback(new Error('请选择往返时间'))
      } else if (value?.[0] === value?.[1]) {
        callback(new Error('往返时间不能一致'))
      } else {
        callback()
      }
    }
    return {
      loading: { 0: false, 1: false }, // 草稿和提交按钮loding
      visible: false, // 人员弹窗控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        usePersonId: []
      }, // 表单
      statusCode: '', // 审批状态
      rules: {
        address: [{ required: true, whitespace: true, message: '请输入目的地', trigger: 'change' }],
        requirement: [{ required: true, whitespace: true, message: '请输入车型要求', trigger: 'change' }],
        phone: [{ required: true, validator: createValidator(isPhone, '请输入正确的手机号码', true), trigger: 'blur' }],
        time: [{ required: true, type: 'array', validator: timeValidator, trigger: 'change' }],
        usePersonId: [{ type: 'array', required: true, message: '请选择用车人员', trigger: 'change' }],
        subjectMatter: [{ required: true, whitespace: true, message: '请输入事由', trigger: 'change' }]
      }, // 校验规则
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  props: {
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  async mounted() {
    this.$route.meta.title = ['用车申请查看', '用车申请编辑', '用车申请新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading[0] = true
      carApplication
        .detail({ id: this.id })
        .then((res) => {
          this.loading[0] = false
          // 设置往返时间
          if (res.data.goTime && res.data.comeTime) {
            res.data.time = [res.data.goTime, res.data.comeTime]
          }
          // 格式化人员
          if (res.data.usePersonId?.length > 0) {
            res.data.usePersonId = res.data.usePersonId?.split(',')?.map((item, index) => ({
              userId: item,
              name: res.data.usePersonNames?.split(';')[index]
            }))
          } else {
            res.data.usePersonId = []
          }
          this.form = res.data
          this.statusCode = res.data?.status // 审批状态
        })
        .catch(() => {
          this.loading[0] = false
        })
    } else {
      const post = this.$currentPost()
      const user = this.$userInfo()
      // 初始化单位
      this.$set(this.form, 'unitName', (post.code === 'PD' ? post.orgName + '-' : '') + post.name)
      this.$set(this.form, 'unitId', post.id)
      this.$set(this.form, 'departmentName', post.deptName)
      // 初始化用户信息
      this.$set(this.form, 'personName', user.name)
      this.$set(this.form, 'phone', user.employee.phoneNum)
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('use_car_application')
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'unitName',
          type: 'BaseInput',
          disabled: true,
          label: '申请单位'
        },
        {
          keyName: 'departmentName',
          type: 'BaseInput',
          disabled: true,
          label: '申请部门'
        },
        {
          keyName: 'personName',
          type: 'BaseInput',
          disabled: true,
          label: '申请人'
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          label: '通知电话'
        },
        {
          keyName: 'address',
          type: 'BaseInput',
          label: '目的地'
        },
        {
          keyName: 'time',
          type: 'a-range-picker',
          // placeholder: '请选择日期',
          label: '往返时间',
          attrs: {
            showTime: { format: 'HH' },
            valueFormat: 'YYYY-MM-DD HH:00',
            dropdownClassName: 'custom-date-offside-style'
          },
          customRender() {
            return arguments[1].goTime && arguments[1].comeTime
              ? arguments[1].goTime + '至' + arguments[1].comeTime
              : '无'
          }
        },
        {
          keyName: 'requirement',
          type: 'BaseInput',
          label: '车型要求'
        },
        {
          keyName: 'usePersonId',
          label: '用车人员',
          slot: true,
          span: 24
        },
        {
          keyName: 'subjectMatter',
          type: 'BaseTextarea',
          label: '事由',
          span: 24,
          attrs: {
            maxLength: 500
          }
        }
      ]
    }
  },
  methods: {
    confirmSelects(data) {
      this.visible = false
      this.form.usePersonId = data
    },
    /**
     * 提交表单
     */
    handleSubmit(statusCode) {
      let that = this
      that.setProcessConfig = null;
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e || statusCode === 0) {
          let name = ['update', 'create'][that.editModel - 1] // 根据操作切换url地址
          statusCode === 0 && that.$refs.ruleForm.clearValidate()
          // 提交表单
          let form = that.$clone(that.form)
          form.status =
            (that.statusCode == '3' && statusCode == 0) || (that.statusCode == '2' && statusCode == 1)
              ? that.statusCode
              : statusCode
          // 设置往返时间参数
          if (form.time?.length > 0) {
            form.goTime = form.time[0]
            form.comeTime = form.time[1]
            delete form.time
          }
          // 格式化用车人员参数
          if (form.usePersonId?.length > 0) {
            form.usePersonId = form.usePersonId.map((item) => item.userId)?.join(',')
          } else {
            delete form.usePersonId
          }
          form.level = that.$currentPost().code
          that.loading[statusCode] = true
          carApplication[name](form)
            .then((res) => {
              that.loading[statusCode] = false
              that.$message.success(['保存', '提交'][statusCode] + '成功！')
              if (statusCode == 1) {
                //提交时，返回id
                that.businessId = res.data?.id;
                that.setProcessConfig = that.processConfig;
                return
              } else {
                that.$multiTab.close()
              }
            })
            .catch(() => {
              // that.$message.warning(['保存', '提交'][statusCode] + '失败！')
              that.loading[statusCode] = false
            })
        }
      })
    }
  }
}
</script>